package com.taoyige.ui;

import java.io.File;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.onekeyshare.OnekeyShare;

import com.taoyige.AppConfig;
import com.taoyige.AppContext;
import com.taoyige.AppException;
import com.taoyige.R;
import com.taoyige.adapter.ListGoodsDetailImagesAdapter;
import com.taoyige.adapter.SlideImageGalleryAdapter;
import com.taoyige.bean.Address;
import com.taoyige.bean.Goods;
import com.taoyige.bean.Order;
import com.taoyige.bean.URLs;
import com.taoyige.common.DPPXUtil;
import com.taoyige.common.FileUtils;
import com.taoyige.common.NumberFormat;
import com.taoyige.common.UIHelper;
import com.taoyige.widget.LoadingDialog;
import com.taoyige.widget.SlideImageGallery;

/**
 * 商品详情页
 * @author peter
 * @version 1.0
 *  @date 2014-11-18
 */
public class GoodsDetailActivity extends BaseActivity {
	
	private AppContext appContext;
	private Handler handler;
	private LoadingDialog loading;
	
	private Goods goods;
	private Long goodsId;
	
	private TextView title;
	private ImageView image;
	private TextView soldCounts;
	private TextView  storeCount;
	private TextView  originPrice;
	private TextView   promotionPrice;
	private TextView   discount;
	private View goodsDetailHeader;
	private List<String> listImages;
	private List<String> listImagesTop;
	private ListView lvImagesDetail;
	private ListGoodsDetailImagesAdapter goodsDetailImagesAdapter;
	private ImageView returnHome;
	private long mHour;  
	private long mMin;  
	private long mSecond;
	private Boolean timeIsRun = true;
	private Boolean allRunning=false;
	
	private LinearLayout goodsDetailAll;
	private RelativeLayout goodsFooter;
	
	private Gallery slideImageGallery;
	private RadioGroup gallery_points;
	private RadioButton[] gallery_point;
	private LinearLayout gallery_layout;
	private Context context;
	private int status;
	private Button ivbuy;
	private LinearLayout main_goods_body;
	private Handler handlerA;
	private Context publicContext;
	private Order publicOrder;
	
	private ImageView detail_share;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main_detail);
		
		appContext=(AppContext) this.getApplication();
		context=getApplicationContext();
		
		this.initView();
		// 网络连接判断
		if (!appContext.isNetworkConnected()){
			detail_share.setOnClickListener(homeOnClickListener);
			returnHome.setOnClickListener(homeOnClickListener);
			goodsFooter.setVisibility(View.INVISIBLE);
			main_goods_body.setVisibility(View.INVISIBLE);
			return;
		}	
		this.initData();
	}
	
	private void initView(){
		goodsId = getIntent().getLongExtra("goodsId", 0l);
		status = getIntent().getIntExtra("status", 0);
		goodsDetailHeader=getLayoutInflater().inflate(R.layout.detail_header,null);
		goodsDetailAll = (LinearLayout)findViewById(R.id.main_goods_detail);
		goodsFooter = (RelativeLayout)findViewById(R.id.goods_main_detail_footer);
		main_goods_body=(LinearLayout)findViewById(R.id.main_goods_body);
		ivbuy = (Button)findViewById(R.id.detail_buy);
		
		title = (TextView)goodsDetailHeader.findViewById(R.id.goods_detail_item_title);
		returnHome=(ImageView)findViewById(R.id.detail_back);
		detail_share=(ImageView) findViewById(R.id.detail_share);
		detail_share.setOnClickListener(shareClickListener);
		//image= (ImageView)goodsDetailHeader.findViewById(R.id.goods_detail_item_image_url);
		
		slideImageGallery = (SlideImageGallery)goodsDetailHeader.findViewById(R.id.slide_image_gallery);
		gallery_points = (RadioGroup) goodsDetailHeader.findViewById(R.id.gallery_raido_group);
		
		soldCounts= (TextView)goodsDetailHeader.findViewById(R.id.detail_index_item_sold);
		originPrice= (TextView)goodsDetailHeader.findViewById(R.id.detail_item_origin_price);
		promotionPrice= (TextView)goodsDetailHeader.findViewById(R.id.detail_index_item_promotion_price);
		discount= (TextView)goodsDetailHeader.findViewById(R.id.detail_index_item_discount);
		
		storeCount= (TextView)findViewById(R.id.detail_footer_store);
		
		lvImagesDetail = (ListView) findViewById(R.id.lv_images_detail);

	}
	

	private void initData() {
		handler = new Handler() {
			public void handleMessage(Message msg) {
				if (msg.what == 1 && msg.obj != null) {
					
					goods = (Goods) msg.obj;
					//加载商品图片
					//UIHelper.showGoodsImage(image, goods.getBannerUrl());
					
					title.setText(goods.getTitle());
					soldCounts.setText(goods.getSalesVolume()+"人已抢购");
					storeCount.setText(goods.getCount()+" ");
					originPrice.setText("原价:￥"+goods.getOriPrice());
					promotionPrice.setText("￥"+goods.getPrice());
					Double disc=(goods.getPrice()/goods.getOriPrice())*10;
					if(disc>1){
						DecimalFormat df = new DecimalFormat("#.0");
				        discount.setText(df.format(disc)+"折");
					}else{
						  discount.setText("0.1折");
					}
			        
			        listImages=goods.getDetailsImageUrl();
					goodsDetailImagesAdapter = new ListGoodsDetailImagesAdapter(GoodsDetailActivity.this, listImages,R.layout.detail_listitem);
					lvImagesDetail.addHeaderView(goodsDetailHeader);
					lvImagesDetail.setAdapter(goodsDetailImagesAdapter);
					
					listImagesTop=goods.getLargeImageUrl();
					initImageGallery(listImagesTop);

					if(status==1){
						if(loading!=null)loading.dismiss();
						ivbuy.setTextSize(20);
						ivbuy.setText("即将开始");
						ivbuy.setBackgroundDrawable(getResources().getDrawable(R.drawable.operation_background_81));
						goodsDetailAll.setVisibility(View.VISIBLE);
						goodsFooter.setVisibility(View.VISIBLE);
					}else{
						if(loading!=null)loading.dismiss();
						if(goods.getServerTime().after(goods.getSaleStartTime())){
							Order order=new Order();
							order.setProduct(goods);
							order.setTotalPrice(goods.getPrice()+goods.getFreight());
							ivbuy.setTextSize(20);
							ivbuy.setText("立刻闪购");
							ivbuy.setTag(order);
							ivbuy.setOnClickListener(ivbuyClickListener);
						}else{
							Date begin = goods.getServerTime();
							Date end = goods.getSaleStartTime();
							long l=end.getTime()-begin.getTime();   
							mHour=(l/(60*60*1000));
							mMin=((l/(60*1000))-mHour*60);   
							mSecond=(l/1000-mHour*60*60-mMin*60);  
							showTheTime();
							timeRun();
						}
						goodsDetailAll.setVisibility(View.VISIBLE);
						goodsFooter.setVisibility(View.VISIBLE);
					}
					//setListViewHeight(lvImagesDetail);
				}else if(msg.what==2){
					if (mHour==0&&mMin==0&&mSecond==0) {  
						timeIsRun=false;
						Order order=new Order();
						order.setProduct(goods);
						order.setTotalPrice(goods.getPrice()+goods.getFreight());
						ivbuy.setTextSize(20);
						ivbuy.setText("立刻闪购");
						ivbuy.setTag(order);
						ivbuy.setOnClickListener(ivbuyClickListener);
					}else{
						mSecond--;
						if(mSecond < 0&&mHour>0) {
							mSecond=59;
							mMin--;
							if(mMin<0){
								mHour--;
								mMin=59;
							}
						}else if(mSecond < 0&&mHour==0) {
							if(mMin>0){
								mSecond=59;
								mMin--;
							}else if(mMin==0){
								mSecond=0;
							}
						}
						showTheTime();
					}
				} else if (msg.obj != null) {
					((AppException) msg.obj).makeToast(GoodsDetailActivity.this);
				}
			}
		};
		returnHome.setOnClickListener(homeOnClickListener);
		this.loadGoodsDetailThread(goodsId);
	}
	
	private void showTheTime(){
		ivbuy.setTextSize(16);
		if(mHour<=0){
			ivbuy.setText("倒计时"+NumberFormat.format(mMin+"")+":"+NumberFormat.format(mSecond+""));
		}else{
			ivbuy.setText("倒计时"+mHour+"小时");
		}
	}

	private void loadGoodsDetailThread(final Long goodsId) {
		goodsDetailAll.setVisibility(View.INVISIBLE);
		goodsFooter.setVisibility(View.INVISIBLE);
		
		loading = new LoadingDialog(this);
		loading.show();
		
		new Thread() {
			public void run() {
				Message msg = new Message();
				try {
					Goods  goods= ((AppContext) getApplication()).getGoodsDetail(goodsId);
					msg.what = 1;
					msg.obj = goods;
				} catch (AppException e) {
					e.printStackTrace();
					msg.what = -1;
					msg.obj = e;
				}
				handler.sendMessage(msg);
			}
		}.start();
	}
    
	//初始化
		void initImageGallery(List<String> list){
			
			//GalleryIndexAdapter adapter = new GalleryIndexAdapter(list, context);
			
//			ArrayList<Integer> ll = new ArrayList<Integer>();
//			ll.add(R.drawable.demo_goods);
//			ll.add(R.drawable.demo_cs);
//			ll.add(R.drawable.demo_goods);
			//SlideImageGalleryAdapter adapter=new SlideImageGalleryAdapter(GoodsDetailActivity.this, list);
			
			SlideImageGalleryAdapter adapter=new SlideImageGalleryAdapter(GoodsDetailActivity.this, list,R.layout.img_switcher);
			
			slideImageGallery.setAdapter(adapter);
			//设置小按钮
			gallery_point = new RadioButton[list.size()];
			for (int i = 0; i < gallery_point.length; i++) {
				gallery_layout = (LinearLayout) getLayoutInflater().inflate(R.layout.img_gallery_icon, null);
				gallery_point[i] = (RadioButton) gallery_layout.findViewById(R.id.gallery_radiobutton);
				gallery_point[i].setId(i);/* 设置指示图按钮ID */
				int wh = DPPXUtil.dp2px(context, 10);
				RadioGroup.LayoutParams layoutParams = new RadioGroup.LayoutParams(wh, wh); // 设置指示图大小
				gallery_point[i].setLayoutParams(layoutParams);
				layoutParams.setMargins(4, 0, 4, 0);// 设置指示图margin值
				gallery_point[i].setClickable(false);/* 设置指示图按钮不能点击 */
				gallery_layout.removeView(gallery_point[i]);//一个子视图不能指定了多个父视图
				gallery_points.addView(gallery_point[i]);/* 把已经初始化的指示图动态添加到指示图的RadioGroup中 */
			}
			
			slideImageGallery.setOnItemSelectedListener(new OnItemSelectedListener() {
				@Override
				public void onItemSelected(AdapterView<?> arg0, View arg1,
						int arg2, long arg3) {
					gallery_points.check(gallery_point[arg2%gallery_point.length].getId());
				}
				@Override
				public void onNothingSelected(AdapterView<?> arg0) {
				}
			});
			
		}
		
		/** 展示图控制器，实现展示图切换 */
		final Handler handlerGallery = new Handler() {
			public void handleMessage(Message msg) {
				/* 自定义屏幕按下的动作 */
				MotionEvent e1 = MotionEvent.obtain(SystemClock.uptimeMillis(),
						SystemClock.uptimeMillis(), MotionEvent.ACTION_UP,
						89.333336f, 265.33334f, 0);
				/* 自定义屏幕放开的动作 */
				MotionEvent e2 = MotionEvent.obtain(SystemClock.uptimeMillis(),
						SystemClock.uptimeMillis(), MotionEvent.ACTION_DOWN,
						300.0f, 238.00003f, 0);
				
				slideImageGallery.onFling(e2, e1, -800, 0);
				/* 给gallery添加按下和放开的动作，实现自动滑动 */
				super.handleMessage(msg);
			}
		};
		
		private void galleryAuto() {
			/* 设置定时器，每5秒自动切换展示图 */
			Timer time = new Timer();
			TimerTask task = new TimerTask() {
				@Override
				public void run() {
					Message m = new Message();
					handlerGallery.sendMessage(m);
				}
			};
			time.schedule(task, 8000, 5000);
		}
		
		
		protected void onResume() {
			galleryAuto();
			super.onResume();
		};
		
		
		private View.OnClickListener homeOnClickListener = new View.OnClickListener() {
			public void onClick(View v) {
				UIHelper.showHomePage(v.getContext());
				
			}
		};
		private View.OnClickListener shareClickListener = new View.OnClickListener() {
			public void onClick(View v) {
				String imageUrl = URLs.STATIC_HOST+goods.getNormalImageUrl().get(0);
//				UIHelper.showShareDialog(GoodsDetailActivity.this,goods.getTitle(), "http://www.taoyige.com",imageUrl);
				showShare(imageUrl);
			}
		};
		
		private void showShare(String imageUrl) {
			String taoyigeSite="http://www.taoyige.com";
			 ShareSDK.initSDK(this);
			 OnekeyShare oks = new OnekeyShare();
			 oks.disableSSOWhenAuthorize(); 
			 oks.setNotification(R.drawable.icon_nt, getString(R.string.app_name));
			 oks.setSilent(false);
			 oks.setDialogMode();
			 oks.setTitle("淘一个");
			 oks.setTitleUrl(taoyigeSite);
			 oks.setText(goods.getTitle()+"详情请访问"+taoyigeSite);
			 oks.setImageUrl(imageUrl);			  
			 oks.setUrl(taoyigeSite);
			 oks.setSite("淘一个");
			 oks.setSiteUrl(taoyigeSite);

			 oks.show(this);
			 }
		
		private View.OnClickListener ivbuyClickListener = new View.OnClickListener() {
			public void onClick(View v) {
				if(goods.getCount()!=0){
				publicContext = v.getContext();
				if(appContext.isLogin()){
					publicOrder = (Order)v.getTag();
					handlerA = new Handler(){
						public void handleMessage(Message msg) {
							if (loading != null)
								loading.dismiss();
							if (msg.what == 1 && msg.obj != null) {
								List<Address> addressList = (List<Address>) msg.obj;
								Address address = addressList.get(0);
								Address addressStatus = addressList.get(1);
								if(addressStatus.getResult().getErrorCode()==200){
									if(address.getResult().getErrorCode()==200&&address.getId()!=null){
										UIHelper.showBuyNow(publicContext,publicOrder,1);
										finish();
									}else{
										Intent intent = new Intent(publicContext, AddressDetailActivity.class);
										intent.putExtra("order", publicOrder);
										intent.putExtra("status", 1);
										publicContext.startActivity(intent);
										finish();
									}
								}else{
									UIHelper.ToastMessage(GoodsDetailActivity.this, addressStatus.getResult().getErrorMessage());
								}
							}else if (msg.obj != null) {
								((AppException) msg.obj).makeToast(GoodsDetailActivity.this);
							}
						}
					};
					new Thread() {
						public void run() {
							Message msg = new Message();
							try {
								Address addr= appContext.getAddrDefault(appContext.getLoginUid());
								Address goodsStatus = appContext.getGoodsBuyStatus(appContext.getLoginUid(),goods.getId());
								List<Address> address = new ArrayList<Address>();
								address.add(addr);
								address.add(goodsStatus);
								msg.what = 1;
								msg.obj = address;
							} catch (AppException e) {
								e.printStackTrace();
								msg.what = -1;
								msg.obj = e;
							}
							handlerA.sendMessage(msg);
						}
					}.start();
				}else{
					UIHelper.showUserLogin(v.getContext(),AppConfig.LOGIN_TYPE_USER_AVATAR_BUTTON);
				}
				}else{
					UIHelper.ToastMessage(GoodsDetailActivity.this,"商品库存不足");
					return;
				}
			}
		};
		
		private void timeRun(){
			new Thread(){  
				public void run() {  
					while (timeIsRun) {  
						Message msg = new Message();
						try {
							Thread.sleep(1000);
							msg.what = 2; 
						} catch (InterruptedException e) {
							e.printStackTrace();
							msg.what = -1;
							msg.obj = e;
						}  
						handler.sendMessage(msg);
					}
				}
			}.start();  
		}
		
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		return false;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}
}
